﻿#_*_ coding: UTF-8 _*_

from core import uicomponents, db, html_utils
from PyQt4 import QtGui, QtCore
from servers.comment.definitions import *
from ui_basic_classes import MainView,NiceTextEdit
from classes import *
import servers.quran.ui


class CommentView(QtGui.QFrame):
	def __init__(self,parent=None):
		QtGui.QFrame.__init__(self,parent)

		self.editor = QtGui.QTextBrowser()
		self.editor.setReadOnly(False)

		self.controlToolBar = QtGui.QToolBar()
		self.controlToolBar.setMaximumHeight(40)

		self.boldAction = QtGui.QAction(QtGui.QIcon(QtGui.QPixmap("images/bold.png")),u"درشت",self.controlToolBar)
		self.boldAction.setShortcut('Ctrl+B')
		self.connect(self.boldAction,QtCore.SIGNAL("triggered()"),self.boldSelection)

		self.saveAction = QtGui.QAction(QtGui.QIcon(QtGui.QPixmap("images/save.png")),u"ذخيره",self.controlToolBar)
		self.saveAction.setShortcut('Ctrl+S')

		self.delAction = QtGui.QAction(QtGui.QIcon(QtGui.QPixmap("images/delete.png")),u"حذف",self.controlToolBar)
		self.delAction.setShortcut('Ctrl+D')

		self.embedded = QtGui.QCheckBox(u"نمايش در متن")

		self.controlToolBar.addAction(self.boldAction)
		self.controlToolBar.addSeparator()
		self.controlToolBar.addAction(self.saveAction)
		self.controlToolBar.addSeparator()
		self.controlToolBar.addWidget(self.embedded)
		self.controlToolBar.addSeparator()
		self.controlToolBar.addAction(self.delAction)

		self.mlayout = QtGui.QVBoxLayout()
		self.mlayout.addWidget(self.controlToolBar)		
		self.mlayout.addWidget(self.editor)

		self.setLayout(self.mlayout)

		
	def boldSelection(self):
		a = self.editor.currentCharFormat()
		if a.fontWeight() == QtGui.QFont.Black :
			a.setFontWeight(QtGui.QFont.Normal)
		else:	
			a.setFontWeight(QtGui.QFont.Black)	
		self.editor.setCurrentCharFormat(a)

		a = self.editor.textCursor().charFormat()
		if a.fontWeight() == QtGui.QFont.Black :
			a.setFontWeight(QtGui.QFont.Normal)
		else:	
			a.setFontWeight(QtGui.QFont.Black)	
		self.editor.textCursor().setCharFormat(a)


class QuranCommentView(MainView):
	def __init__(self,parent=None):
		MainView.__init__(self,parent)
		self.commentList = QtGui.QListWidget()
		self.commentList.setMaximumHeight(150)
		self.commentList.setMinimumHeight(20)
		self.comment = CommentView()

		self.connect(self.comment.saveAction,QtCore.SIGNAL("triggered()"),self.saveThisComment)
		self.connect(self.comment.delAction,QtCore.SIGNAL("triggered()"),self.delThisComment)

		llayout = QtGui.QVBoxLayout()
		llayout.addWidget(self.commentList)
		llayout.addWidget(self.comment)

		self.setLayout(llayout)
		QtCore.QObject.connect(servers.quran.ui.quranBrowser.quran.quran,QtCore.SIGNAL("selectionChanged()"),self.showCurrentComments)
		QtCore.QObject.connect(self.commentList,QtCore.SIGNAL("currentRowChanged(int)"),self.showThisComment)

	
	def saveThisComment(self):
		self.comments[self.commentList.currentRow()].fa = unicode(self.comment.editor.toHtml()).encode("utf-8")
		if self.comment.embedded.isChecked():
			self.comments[self.commentList.currentRow()].embedded = 1
		else:
			self.comments[self.commentList.currentRow()].embedded = 0
		session.flush()

	def delThisComment(self):
		c = self.comments.pop(self.commentList.currentRow())
		session.delete(c)
		for cw in c.words:
			del cw
		del c	
		session.flush()
		servers.quran.ui.quranBrowser.quran.refreshWithPath()		
		self.showCurrentComments()

	def showThisComment(self,commentNumber):
		if commentNumber == -1:
			return
		self.comment.embedded.setChecked(self.comments[commentNumber].embedded)
		self.comment.editor.setHtml(unicode(self.comments[commentNumber].fa,"utf-8"))

	def showCurrentComments(self):
		self.comments=[]
		self.commentList.clear()
		self.comment.editor.setHtml("");
		temp = {}
		if uicomponents.SharedUi.applications['QuranComment']['docables']['all'].isVisible():
			servers.quran.ui.quranBrowser.quran.selectionControl()
			w = uicomponents.SharedUi.selectionStartWord
			while True:	
				try:
					session.refresh(w)
					for c in w.comments:
						temp[c.comment] = 1
					if w == uicomponents.SharedUi.selectionEndWord:
						break
				except:
					pass
				w = w.next()

			self.comments = temp.keys()	
			for c in self.comments:
				s = ""
				for w in c.words:
					s += w.word.word
					if not w.last:
						s += " "
				self.commentList.addItem(unicode(s,"utf-8"))
	def insertComment(self):
		c = qComment()
		c.embedded = 1
		c.fa = ""
		session.flush()
		servers.quran.ui.quranBrowser.quran.selectionControl()
		w = uicomponents.SharedUi.selectionStartWord
		while True:
			w.comments.append(qWordComment())
			w.comments[-1].comment = c
			session.flush()		
			if w == uicomponents.SharedUi.selectionEndWord:
				w.comments[-1].last = 1
				session.flush()
				break
			else:
				w = w.next()
		self.showNow()
	
	def showNow(self):
		showView()
		self.showCurrentComments()


def showView():
	if not uicomponents.SharedUi.applications['QuranComment']['docables']['all'].isVisible():
		uicomponents.SharedUi.mainWindow.addDockWidget(QtCore.Qt.BottomDockWidgetArea,uicomponents.SharedUi.applications['QuranComment']['docables']['all'])
		uicomponents.SharedUi.applications['QuranComment']['docables']['all'].show()
	
uicomponents.SharedUi.applications['QuranComment']  = {}
uicomponents.SharedUi.applications['QuranComment']['actionSlot'] = showView
uicomponents.SharedUi.applications['QuranComment']['name']  = u'توضيح آيه'
uicomponents.SharedUi.applications['QuranComment']['shortcut'] = u'Ctrl+E'
uicomponents.SharedUi.applications['QuranComment']['docables']={}
uicomponents.SharedUi.applications['QuranComment']['docables']['all'] = QtGui.QDockWidget(uicomponents.SharedUi.mainWindow)
uicomponents.SharedUi.applications['QuranComment']['docables']['all'].setWindowTitle(u'توضيح قرآن')
uicomponents.SharedUi.applications['QuranComment']['docables']['all'].resize(500,100)
quranComment = QuranCommentView()
uicomponents.SharedUi.applications['QuranComment']['docables']['all'].setWidget(quranComment)
uicomponents.SharedUi.applications['QuranComment']['docables']['all'].hide()


showSelectionComment = QtGui.QAction(u'توضيح', None)
showSelectionComment.setShortcut('Ctrl+J')
uicomponents.SharedUi.wordPopupMenu.addAction(showSelectionComment)
uicomponents.SharedUi.ayePopupMenu.addAction(showSelectionComment)
uicomponents.SharedUi.modulesListMenu.addAction(showSelectionComment)
QtCore.QObject.connect(showSelectionComment, QtCore.SIGNAL('triggered()'), quranComment.showNow)


addSelectionComment = QtGui.QAction(u'افزودن توضيح',None)
addSelectionComment.setShortcut(u'Ctrl+I')
uicomponents.SharedUi.wordPopupMenu.addAction(addSelectionComment)
uicomponents.SharedUi.ayePopupMenu.addAction(addSelectionComment)
uicomponents.SharedUi.modulesListMenu.addAction(addSelectionComment)
QtCore.QObject.connect(addSelectionComment, QtCore.SIGNAL('triggered()'), quranComment.insertComment)


def maskAllah(word,w):
	if word.noErabWord in ['الله','اله','لله','رب']:
		return '<font color=red><b>%s</b></font>' % w
	return w	

def commentWord(word,w):
	s = ""
	try:
		for c in word.comments:
			if c.comment.embedded and c.last:
				if len(s)>0:
					s += ", "
				s += c.comment.fa 
	except:
		pass
	if len(s)>0:		
		return w+ u" <font color=green face='B Lotus'>[%s]</font> " % unicode(html_utils.remove_html_tags(s),"utf-8")
	else:
		return w

servers.quran.definitions.quranWordMasks['الله'] = maskAllah
servers.quran.definitions.quranWordCommenters['توضيح']=commentWord
print "comment module Added!"
